var web = web || {};
web.Rating = Class.create(); 
web.Rating.prototype = {
	initialize: function(elem, options) {
		var _this = this;
		this.settings = $.extend({
			num: 5,
			onChangeRate: function(level){},
			onClick: function(level){},
			half: false
		}, options);
		
		this.element = elem;
		this.rate = elem.children('div');
		this.input = elem.children('input');
		
		this.width = this.rate.innerWidth();
		this.offset = this.rate.offset();
		this.startWidth = parseInt(this.width / this.settings.num);
		this.currentlyLevel = 0;
		this.defaultLevel = 0;
		
		this._init();
	},
	_init: function() {
		var _this = this;
		
		var v = Number(this.input.val());
		if (isNaN(v)) v = 0;
		this.defaultLevel = v * 10;;
		this._changeCss(this.defaultLevel);
		
		this.rate.bind('mousemove', function(event){
			var x = event.pageX;
			_this._showRate(x);
		}).bind('mouseleave', function(event){
			_this._changeCss(_this.defaultLevel);
		}).bind('click', function(){
			_this._setRateVal();
		});
	},
	_showRate: function(x) {
		var rateX = parseInt(x - this.offset.left);
		var n = Number(rateX / this.startWidth).toFixed(1);
		var l = (n - parseInt(n)) >= 0.5 ? 10 : 5;
		
		if (!this.settings.half) {
			if (5 == l) l = 10;
		}
		
		var level =  parseInt(n) * 10 + l;
		if (level != this.currentlyLevel) {
			this._changeCss(level);
		}
	},
	_setRateVal: function() {
		var v = Number(this.currentlyLevel / 10).toFixed(1);
		if (!this.settings.half) {
			v = parseInt(v);
		}
		this.defaultLevel = this.currentlyLevel;
		this.input.val(v);
		this.settings.onClick.call(this, v);
	},
	_changeCss: function(level) {
		this.rate.removeClass(this._getCss());
		this.currentlyLevel = level;
		this.rate.addClass(this._getCss());
		if ($.isFunction(this.settings.onChangeRate)) {
			this.settings.onChangeRate.call(this, level);
		}
	},
	_getCss: function() {
		return 'r' + this.currentlyLevel;
	}
};

;(function($) {
	$.fn.rating = function(options) {
		return this.each(function(){
			new web.Rating($(this), options);
		});
	}
})(jQuery);